﻿using System;
using System.Collections.Generic;
using System.Drawing;
using GeoSketch2.Core;
using System.Xml;
using System.IO;

namespace GeoSketch2.Archaeo
{
    /// <summary>
    /// The polyline object for the Archaeo module
    /// </summary>
    public class Polyline : BaseArchaeoDrawableObject
    {
        #region XMLElementsName
#pragma warning disable 1591
        public const string XML_Vertices = "Vertices";
#pragma warning restore 1591
        #endregion

        #region Fields
        /// <summary>
        /// The vertices list of the polyline
        /// </summary>
        public List<Vertex> Vertices; 
        #endregion

        #region Constructor
        /// <summary>
        /// The polyline object for the Archaeo module
        /// </summary>
        /// <param name="Vertices">The vertices list of the polyline, if null a new polyline will be created</param>
        /// <param name="Layer">The layer of the polyline</param>
        /// <param name="ExcavationUnit">The excavation unit of the polyline</param>
        public Polyline(List<Vertex> Vertices, Layer Layer, ExcavationArea ExcavationUnit)
            : this(Vertices, Layer, ExcavationUnit, LineTypeByLayer())
        {
        } 

        /// <summary>
        /// The polyline object for the Archaeo module
        /// </summary>
        /// <param name="Vertices">The vertices list of the polyline, if null a new polyline will be created</param>
        /// <param name="Layer">The layer of the polyline</param>
        /// <param name="ExcavationUnit">The excavation unit of the polyline</param>
        /// <param name="LineType">The type of line of the polyline</param>
        public Polyline(List<Vertex> Vertices, Layer Layer, ExcavationArea ExcavationArea, LineType LineType)
            : this(Vertices, Layer, ExcavationArea, LineType, ColorByLayer())
        {
        } 

        /// <summary>
        /// The polyline object for the Archaeo module
        /// </summary>
        /// <param name="Vertices">The vertices list of the polyline, if null a new polyline will be created</param>
        /// <param name="Layer">The layer of the polyline</param>
        /// <param name="ExcavationUnit">The excavation unit of the polyline</param>
        /// <param name="LineType">The type of line of the polyline</param>
        /// <param name="Color">The color of the polyline</param>
        public Polyline(List<Vertex> Vertices, Layer Layer, ExcavationArea ExcavationArea, LineType LineType, Color Color)
            : this(Vertices, Layer, ExcavationArea, LineType, Color, "")
        {
        } 

        /// <summary>
        /// The polyline object for the Archaeo module
        /// </summary>
        /// <param name="Vertices">The vertices list of the polyline, if null a new polyline will be created</param>
        /// <param name="Layer">The layer of the polyline</param>
        /// <param name="ExcavationUnit">The excavation unit of the polyline</param>
        /// <param name="LineType">The type of line of the polyline</param>
        /// <param name="Color">The color of the polyline</param>
        /// <param name="Comment">The comment about of the point</param>
        public Polyline(List<Vertex> Vertices, Layer Layer, ExcavationArea ExcavationArea, LineType LineType, Color Color, string Comment)
            : this(Vertices, Layer, ExcavationArea, LineType, Color, Comment, DateTime.Now)
        {
        } 

        /// <summary>
        /// The polyline object for the Archaeo module
        /// </summary>
        /// <param name="Vertices">The vertices list of the polyline, if null a new polyline will be created</param>
        /// <param name="Layer">The layer of the polyline</param>
        /// <param name="ExcavationUnit">The excavation unit of the polyline</param>
        /// <param name="LineType">The type of line of the polyline</param>
        /// <param name="Color">The color of the polyline</param>
        /// <param name="Comment">The comment about of the point</param>
        /// <param name="CreationTime">The date of creation of the object</param>
        public Polyline(List<Vertex> Vertices, Layer Layer, ExcavationArea ExcavationArea, LineType LineType, Color Color, string Comment, DateTime CreationTime)
            : base(Layer, Color, LineType, ExcavationArea, Comment, CreationTime)
        {
            if (Vertices == null)
            {
                Vertices = new List<Vertex>();
            }

                this.Vertices = Vertices;
        }

        /// <summary>
        /// The polyline object for the Archaeo module
        /// </summary>
        /// <param name="Xr">The XmlReader to read from</param>
        /// <param name="Site">The site of the object</param>
        public Polyline(XmlReader Xr, ArchaeoProject Project)
            : base(Xr, Project)
        {
            Vertices = new List<Vertex>();

            Xr.ReadToFollowing(XML_SpecificInfos);

            #region Vertices
            Xr.ReadToFollowing(XML_Vertices);
            if (!Xr.IsEmptyElement)
            {
                Xr.ReadToFollowing(typeof(Vertex).Name);
                while (!(Xr.NodeType == XmlNodeType.EndElement && Xr.Name == XML_Vertices))
                {
                    Vertices.Add(new Vertex(Xr));
                    Xr.ReadEndElement();
                }
                Xr.ReadEndElement();
            }
            Xr.ReadEndElement();
            #endregion
        }
        #endregion

        #region Methods
        /// <summary>
        /// The drawing method of the polyline when selected
        /// </summary>
        /// <param name="Viewport">The viewport to draw to</param>
        protected override void DrawSelected(BaseViewport Viewport)
        {
            DrawCustomPen(Viewport, Core.Vars.Setup.Tools.TSelection.SelectionPen);
        }

        /// <summary>
        /// The drawing method of the polyline when not selected
        /// </summary>
        /// <param name="Viewport">The viewport to draw to</param>
        protected override void DrawUnselected(BaseViewport Viewport)
        {
            DrawCustomPen(Viewport, Pen);
        }

        /// <summary>
        /// The draw method for each object with a custom pen
        /// </summary>
        /// <param name="Viewport">The viewport to draw to</param>
        /// <param name="CustomPen">The custom pen object to draw the object with</param>
        public override void DrawCustomPen(BaseViewport Viewport, Pen CustomPen)
        {
            Arc temp_arc;
            for (int i = 0; i < Vertices.Count - 1; i++)
            {
                if (Vertices[i].Type == VertexType.Line)
                {
                    Viewport.Graphic.DrawLine(CustomPen,
                       Viewport.Object2ImageTransformation.Transform(Vertices[i].Position),
                       Viewport.Object2ImageTransformation.Transform(Vertices[i + 1].Position));
                }
                else if (Vertices[i].Type == VertexType.Arc)
                {
                    if (Vertices.Count > i + 2)
                    {
                        temp_arc = new Arc(Viewport.Object2ImageTransformation.Transform(Vertices[i].Position),
                                Viewport.Object2ImageTransformation.Transform(Vertices[i + 1].Position),
                                Viewport.Object2ImageTransformation.Transform(Vertices[i + 2].Position));
                        Viewport.Graphic.DrawArc(CustomPen, temp_arc.EllipseBound, temp_arc.StartAngle, temp_arc.SweepAngle);
                        i++;
                    }
                }
            }
        }

        /// <summary>
        /// The method to return whether the object is near to the clic or not
        /// </summary>
        /// <param name="Clic">The point clicked in object coordinates</param>
        /// <param name="IsNearDistance">The distance under which the clic is near to the object</param>
        public override bool IsNear(Point2D64D Clic, double IsNearDistance)
        {
            for (int i = 0; i < Vertices.Count - 1; i++)
            {
                if (Vertices[i].Type == VertexType.Line)
                {
                    if (Clic.DistancePointLine(Vertices[i].Position, Vertices[i + 1].Position) < IsNearDistance)
                    {
                        Point2D64D center = (Vertices[i].Position + Vertices[i + 1].Position) * 0.5;
                        if (2 * center.Distance2DSqr(Clic) < Vertices[i].Position.Distance2DSqr(Vertices[i + 1].Position) + Core.Vars.Setup.Tools.TSelection.IsNearDistance * Core.Vars.Setup.Tools.TSelection.IsNearDistance)
                        {
                            return true;
                        }
                    }
                }
                else if (Vertices[i].Type == VertexType.Arc)
                {
                    i++;
                }
            }
            return false;
        }

        /// <summary>
        /// Returns the nearest line to the click, null if none
        /// </summary>
        /// <param name="Clic">The point clicked in object coordinates</param>
        /// <param name="IsNearDistance">The distance under which the clic is near to the object</param>
        public override Line2D64D NearestLine(Point2D64D Clic, double IsNearDistance)
        {
            Line2D64D dst=null;

            for (int i = 0; i < Vertices.Count - 1; i++)
            {
                if (Vertices[i].Type == VertexType.Line)
                {
                    if (Clic.DistancePointLine(Vertices[i].Position, Vertices[i + 1].Position) < IsNearDistance)
                    {
                        Point2D64D center = (Vertices[i].Position + Vertices[i + 1].Position) * 0.5;
                        if (2 * center.Distance2DSqr(Clic) < Vertices[i].Position.Distance2DSqr(Vertices[i + 1].Position) + Core.Vars.Setup.Tools.TSelection.IsNearDistance * Core.Vars.Setup.Tools.TSelection.IsNearDistance)
                        {
                            dst = new Line2D64D(Vertices[i].Position, Vertices[i + 1].Position);
                            break;
                        }
                    }
                }
                else if (Vertices[i].Type == VertexType.Arc)
                {
                    i++;
                }
            }
            return dst;
        }

        /// <summary>
        /// Returns the nearest point to the click, null if none
        /// </summary>
        /// <param name="Clic">The point clicked in object coordinates</param>
        /// <param name="IsNearDistance">The distance under which the clic is near to the object</param>
        public override Point2D64D NearestPoint(Point2D64D Clic, double IsNearDistance)
        {
            Point2D64D dst=null;

            for (int i = 0; i < Vertices.Count; i++)
            {
                if (Clic.Distance2D(Vertices[i].Position) < IsNearDistance)
                {
                    dst = Vertices[i].Position;
                }
            }

            return dst;
        }

        /// <summary>
        /// Clones the object
        /// </summary>
        public override T Clone<T>()
        {
            return (T)(object)new Polyline(Vertices.DeepClone<List<Vertex>>(), Layer, ExcavationArea, this._LineType, this._ObjectColor, Comment);
        }

        /// <summary>
        /// Translates the object
        /// </summary>
        /// <param name="Vector">The translation vector</param>
        public override void Translate(Point2D64D Vector)
        {
            foreach (Vertex v in Vertices)
            {
                v.Position.X += Vector.X;
                v.Position.Y += Vector.Y;
            }
        }

        /// <summary>
        /// Writes the object to a file
        /// </summary>
        /// <param name="Xw">The Xml Writer to write to</param>
        public override void ToFile(XmlWriter Xw)
        {
            Xw.WriteStartElement(this.GetType().FullName);

            #region Object Base Information
            this.BaseInfosToFile(Xw);
            #endregion

            #region Object Specific Information
            Xw.WriteStartElement(XML_SpecificInfos);

            #region Vertices
            Xw.WriteStartElement(XML_Vertices);
            foreach (Vertex v in this.Vertices)
            {
                v.ToFile(Xw);
            }
            Xw.WriteEndElement();
            #endregion

            Xw.WriteEndElement();
            #endregion

            Xw.WriteEndElement();
        }

        public override void ToDXFr13(TextWriter Tw)
        {
            Tw.WriteLine("0");
            Tw.WriteLine("POLYLINE");

            this.BaseInfosToDXFR13(Tw);

            /*if (Vertices[0].Position == Vertices[Vertices.Count - 1])
            {
                Tw.WriteLine("70");
                Tw.WriteLine("1");
            }*/

            Tw.WriteLine("66");
            Tw.WriteLine("1");

            Tw.WriteLine("10");
            Tw.WriteLine("0.0");

            Tw.WriteLine("20");
            Tw.WriteLine("0.0");

            Tw.WriteLine("30");
            Tw.WriteLine("0.0");

            for (int i = 0; i < Vertices.Count; i++)
            {
                Tw.WriteLine("0");
                Tw.WriteLine("VERTEX");

                this.BaseInfosToDXFR13(Tw);

                Vertices[i].ToDXFR13(Tw);

                if (Vertices[i].Type == VertexType.Arc)
                {
                    Arc arc = new Arc(Vertices[i].Position, Vertices[i + 1].Position, Vertices[i + 2].Position);
                    
                    Tw.WriteLine("42");
                    Tw.WriteLine((Math.Tan(arc.SweepAngle.Degrees2Radians() / 4)).ToString(Core.Vars.Setup.GeoSketch.NumberFormat));

                    i++;
                }
            }

            Tw.WriteLine("0");
            Tw.WriteLine("SEQEND");
        }
        #endregion

        #region Properties
        /// <summary>
        /// Get the vertices list as an array of Point2Ds
        /// </summary>
        public Point2D64D[] VerticesPoints
        {
            get
            {
                Point2D64D[] dst = new Point2D64D[Vertices.Count];

                for (int i = 0; i < Vertices.Count; i++)
                {
                    dst[i] = Vertices[i].Position;
                }

                return dst;
            }
        }

        /// <summary>
        /// Gets the bounding box of the object, the Y-axis direction of the REctangleD must be upside
        /// </summary>
        public override RectangleD Bounds
        {
            get
            {
                return Tools.GetRectangleDBounds(VerticesPoints, YAxisDirection.UpSide);
            }
        }
        #endregion
    }
}
